package astra.client.pages.purchase;

import astra.client.Astra;
import astra.client.models.Client;
import astra.client.models.Employee;
import astra.client.models.Purchase;
import astra.client.models.Supplier;
import astra.client.pages.clients.ClientsPage;
import astra.client.services.AstraServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DatePicker;

import java.awt.*;

/**
 * @author Kotelnikov Dmitry <a href="mailto:dimonnot@mail.ru"/>
 */
public class PurchasePopup extends DialogBox{
    interface PurchasePopupUiBinder extends UiBinder<HTMLPanel, PurchasePopup> {
    }

    private static PurchasePopupUiBinder ourUiBinder = GWT.create(PurchasePopupUiBinder.class);

    @UiField
    SimplePanel message;
    @UiField
    Button closeButton;
    @UiField
    TextBox address;
    @UiField
    DateBox confirmDate;
    @UiField
    TextBox serviceName;
    @UiField
    ListBox manager;
    @UiField
    TextArea advertisment;
    @UiField
    ListBox model;
    @UiField
    ListBox account;
    @UiField
    TextBox photoReport;
    @UiField
    ListBox supplier;
    @UiField
    Button storeButton;
    @UiField
    ListBox client;
    @UiField
    TextBox contractNumber;
    @UiField
    TextBox material;

    private Astra astra;
    private AstraServiceAsync service;
    private PurchasePage purchasePage;
    private Purchase purchase;

    public PurchasePopup(Astra astra, AstraServiceAsync service, PurchasePage purchasePage) {
        this.astra  = astra;
        this.service = service;
        this.purchasePage = purchasePage;

        HTMLPanel rootElement = ourUiBinder.createAndBindUi(this);
        setWidget(rootElement);

        setWidth("550px");
        setModal(true);
        setGlassEnabled(true);
        setAutoHideEnabled(true);
    }

    public void edit(Purchase purchase) {
        this.client.clear();
        for (Client client: astra.getAstraData().getClients()) {
            this.client.addItem(client.getName(), Integer.toString(client.getId()));
        }

        this.supplier.clear();
        for (Supplier supplier: astra.getAstraData().getSuppliers()) {
            this.supplier.addItem(supplier.getName(), Integer.toString(supplier.getId()));
        }

        this.manager.clear();
        for (Employee employee: astra.getAstraData().getEmployees()) {
            if (employee.getGroupId() == 6) {
                this.manager.addItem(employee.getName(), Integer.toString(employee.getId()));
            }
        }

        this.account.clear();
        for (Employee employee: astra.getAstraData().getEmployees()) {
            if (employee.getGroupId() == 7) {
                this.account.addItem(employee.getName(), Integer.toString(employee.getId()));
            }
        }

        if (purchase != null) {
            setText("Редактирование данных о размещении");
            this.purchase = purchase;
        } else {
            setText("Добавление размещения");
            this.purchase = new Purchase();
        }

        address.setValue(this.purchase.getAddress());
        confirmDate.setValue(this.purchase.getConfirmDate());
        serviceName.setValue(this.purchase.getService());
        for (int i = 0; i < this.supplier.getItemCount(); i++) {
            if (this.supplier.getValue(i).equals(this.purchase.getSupplierId())) {
                this.supplier.setSelectedIndex(i);
                break;
            }
        }

        for (int i = 0; i < this.client.getItemCount(); i++) {
            if (this.client.getValue(i).equals(this.purchase.getClientId())) {
                this.client.setSelectedIndex(i);
                break;
            }
        }

        for (int i = 0; i < this.manager.getItemCount(); i++) {
            if (this.manager.getValue(i).equals(this.purchase.getManagerId())) {
                this.manager.setSelectedIndex(i);
                break;
            }
        }

        for (int i = 0; i < this.account.getItemCount(); i++) {
            if (this.account.getValue(i).equals(this.purchase.getAccountId())) {
                this.account.setSelectedIndex(i);
                break;
            }
        }
        advertisment.setValue(this.purchase.getAdvertisment());
        photoReport.setValue(this.purchase.getPhotoReport());
        contractNumber.setValue(this.purchase.getContractNumber());
        material.setValue(this.purchase.getMaterial());

        center();
        show();
    }

    protected Purchase getPurchase() {
        purchase.setAddress(address.getValue());
        purchase.setConfirmDate(confirmDate.getValue());
        purchase.setService(serviceName.getValue());
        purchase.setAdvertisment(advertisment.getValue());
        purchase.setPhotoReport(photoReport.getValue());
        purchase.setSupplierId(Integer.parseInt(supplier.getValue(supplier.getSelectedIndex())));
        purchase.setClientId(Integer.parseInt(client.getValue(client.getSelectedIndex())));
        purchase.setManagerId(Integer.parseInt(manager.getValue(manager.getSelectedIndex())));
        purchase.setAccountId(Integer.parseInt(account.getValue(account.getSelectedIndex())));
        purchase.setContractNumber(contractNumber.getValue());
        purchase.setMaterial(material.getValue());
        return purchase;
    }

    @UiHandler("closeButton")
    public void onClickCloseButton(ClickEvent event) {
        hide();
    }

    @UiHandler("storeButton")
    public void onClickStoreButton(ClickEvent event) {
        storeButton.setEnabled(false);
        closeButton.setEnabled(false);
        service.store(
            getPurchase(),
            new AsyncCallback<Void>() {
                @Override
                public void onFailure(Throwable caught) {
                    storeButton.setEnabled(true);
                    closeButton.setEnabled(true);
                    astra.onFailure(caught, "Не удается сохранить данные о размещении", message);
                }

                @Override
                public void onSuccess(Void result) {
                    storeButton.setEnabled(true);
                    closeButton.setEnabled(true);
                    hide();
                }
            }
        );
    }
}